#include <stdlib.h>

#include "SDL.h"
#include "SDL_opengl.h"
#include "opengl-rendering.h"
#include "cairo-rendering.h"

#define WIN_WIDTH 720
#define WIN_HEIGHT 576

#define UNUSED(x) (void)x

int main(int argc, char **argv)
{
	UNUSED(argc);
	UNUSED(argv);

	int width = WIN_WIDTH;
	int height = WIN_HEIGHT;
	unsigned int texture_id;
	SDL_Surface *surf_window = NULL;
	SDL_Event event;
	int keep_running = 1;
	cairo_surface_t *surf = NULL;
	cairo_t *cr;
	unsigned char *surf_data;


	// init SDL
	if ((SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) == -1))
	{
		printf("Could not initialize SDL: %s.\n", SDL_GetError());
		exit(-1);
	}

	// set window title
	SDL_WM_SetCaption("gl-cairo-simple", NULL);
	// create "GL-context"
	SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
	SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 6);
	SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
	SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
	surf_window = SDL_SetVideoMode(width, height, 0, SDL_OPENGL | SDL_RESIZABLE);

	// did we get what we want?
	if (!surf_window)
	{
		printf("Couldn't open SDL-window: %s\n", SDL_GetError());
		exit(-2);
	}

	// create cairo-surface/context to act as OpenGL-texture source
	cr = create_cairo_context(width, height, 4, &surf, &surf_data);

	// setup "GL-context"
	init_gl();
	resize_func(width, height, &texture_id);

	// enter event-loop
	while (keep_running)
	{
		// get event from queue
		SDL_PollEvent(&event);

		switch (event.type)
		{
		// check for user hitting close-window widget
		case SDL_QUIT:
			keep_running = 0;
			break;
		}

		render_curve(cr, width, height);
		draw_func(width, height, surf_data, texture_id);

		// try to get a redraw-rate of 50 Hz
		SDL_Delay(20);
	}

	// clear resources before exit
	glDeleteTextures(1, &texture_id);
	free(surf_data);
	cairo_destroy(cr);
	SDL_Quit();

	return 0;
}
